<?php

namespace app\common\model;

use think\Model;


class ActivityOrder extends Model
{

    

    

    // 表名
    protected $name = 'activity_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_type_text',
        'paytime_text',
        'verification_time_text',
        'status_text'
    ];
    

    
    public function getPayTypeList()
    {
        return ['wechat' => __('Pay_type wechat'), 'score' => __('Pay_type score')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getVerificationTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['verification_time']) ? $data['verification_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setVerificationTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function activity()
    {
        return $this->belongsTo('Activity', 'activity_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function paysuccess($order_no,$pay_fee,$pay_type)
    {
        $order = self::get(['order_no'=>$order_no]);
        if($order['status'] != 0){
            return true;
        }
        if($pay_type == 'score'){
            $order->score_fee = $pay_fee;
        }else{
            $order->pay_fee = $pay_fee;
        }
        $order->status = 1;
        $order->paytime = time();
        if($order->save()){
            return true;
        }else{
            return false;
        }
    }
}
